<?php

ini_set("display_errors","1");

class Answer {
    var $code;
    var $message;
    var $data;
    public function __construct($code = "0", $data = null, $message = ""){
        $this->code = $code;
        $this->data = $data;
        $this->message = $message;
    }	
    public function toJSON(){
        $res = array(   "code" => $this->code,
                        "data" => $this->data,
                        "message" => $this->message );
        return json_encode($res);	
    }
}

class Service {
    var $code;
    var $name;
    var $prefix;
}

class Config {
		
    var $currentController;

    private $dependencies = "dependencies";
    private $admins = array(
		"admin" => "123"
	);
	
    public function __construct(){
        $this->initDefines();
        include_once MODELS.'database.php';
        Database::connect();
        ob_start();
    }

    public function __destruct() {
        Database::close();
    }

    public function initDefines(){
        include_once 'src/util/define.php';
    }
    public function initAjax(){
        include_once AJAX;
    }
    public function contentController(){
        include_once CONTENT_CONTROLLER;
    }
    public function functionController(){
        include_once FUNCTION_CONTROLLER;
    }

    public function filter($requestParam, $removeTags = false){
        if(isset($_REQUEST[$requestParam])){
            if(is_string($requestParam)) {
                if(!get_magic_quotes_gpc())
                    $requestParam = addslashes($_REQUEST[$requestParam]);
                $requestParam = trim($requestParam);
                if($removeTags) $requestParam = strip_tags($requestParam);
            }
        } else  {
            $requestParam = null;
        }
        return $requestParam;
    }

    public function maskCPF($cpf){
        $out_cpf = substr($cpf, 0, 3);
        $out_cpf .= ".";
        $out_cpf .= substr($cpf, 3, 3);
        $out_cpf .= ".";
        $out_cpf .= substr($cpf, 6, 3);
        $out_cpf .= "-";
        $out_cpf .= substr($cpf, 9, 2);
        return $out_cpf;
    }
    
    public function maskCEP($cep){
        $out_cep = substr($cep, 0, 2);
        $out_cep .= ".";
        $out_cep .= substr($cep, 2, 3);
        $out_cep .= "-";
        $out_cep .= substr($cep, 5, 3);
        return $out_cep;
    }
    
    public function maskTelefone($telefone){
        $out = "(".substr($telefone, 0, 2).") ";
        $out .= substr($telefone, 2, 4);
        $out .= "-";
        $out .= substr($telefone, 6, 4);
        return $out;
    }
    
    public function maskCNPJ($cnpj){
        $out = substr($cnpj, 0, 2);
        $out .= ".";
        $out .= substr($cnpj, 2, 3);
        $out .= ".";
        $out .= substr($cnpj, 5, 3);
        $out .= "/";
        $out .= substr($cnpj, 8, 4);
        $out .= "-";
        $out .= substr($cnpj, 12, 2);
        return $out;
    }
    
    public function maskData($data){
        return date("d/m/Y", strtotime($data));
    }
    
    public function maskDinheiro($valor){
        return number_format($valor, 2, ",", ".");
    }


    public function throwAjaxSuccess($data){
        $answer = new Answer();
        $answer->data = $data;
        echo $answer->toJSON();
        exit(0);
    }

    public function throwAjaxError($message){
        $answer = new Answer("1", null, $message);
        echo $answer->toJSON();
        exit(0);
    }

    public function loadAjaxService($service_code){
        $str = file_get_contents(SERVICES_FILE);
        $str_services = explode("\n", $str);	
        foreach($str_services as $str_service){
            if(empty($str_service)) continue;

            $service = explode(":", $str_service);

            if($service[0] == $service_code) {
                $servobj = new Service();
                $servobj->code = $service[0];
                $servobj->name = $service[1];
                $servobj->prefix = $service[2];

                return $servobj;
            }
        }
        return null;
    }

    public function requestService($service){
        include_once SERVICES.$service->name.".php";
    }

    public function loadCurrentController($service){
        $prefix = is_string($service) ? $service : $service->prefix; 		
        $fullpath = CONTROLLERS.$prefix.".php";	
        if(file_exists($fullpath)){
            include_once $fullpath;
            $class = ucfirst($prefix)."Controller";
            $this->currentController = new $class();			
        } else {
            $this->throwAjaxError("Falha Interna.\nErro ao carregar controlador");
        }
    }

    public function iniJSDependencies(){
        echo "<script> var {$this->dependencies} = new Array(); </script>";
    }
    
    public function addJSDependencie($query){
        echo "<script> {$this->dependencies}.push(function(){ $query }); </script>";
    }
    
    public function execJSDependencies(){
        echo "<script>";
        echo "for(i = 0; i < {$this->dependencies}.length; i++){";
        echo "{$this->dependencies}[i]();";
        echo "}";
        echo "</script>";   
    }

    public function successInFunction($detail = null){
        $message = "+Sucesso na operação";
        if(!is_null($detail))
            $message .= "<br/>$detail";
        $this->recordMessage($message);
    }

    public function failInFunction($detail = null){
        $message = "-Falha na operação";
        if(!is_null($detail))
            $message .= "<br/>$detail";
        $this->recordMessage($message);
    }
    
    private function recordMessage($message){ 
        setcookie(MESSAGE_COOKIE, $message, 0, "/");
    }
    public function checkMessage(){
        if(isset($_COOKIE[MESSAGE_COOKIE]) && !empty($_COOKIE[MESSAGE_COOKIE])){
            $message = $_COOKIE[MESSAGE_COOKIE];
            $alert = "alert";
            if(! strcmp(substr($message, 0, 1), "-") ) $alert = "badAlert";
            $message = substr($message, 1);
			$message = " $alert(\"$message\"); ";            
			setcookie(MESSAGE_COOKIE, "", 1, "/");
			return $message;
		}
		return "";
    }

    public function redirect($page, $countdown = 0){
        unset($_POST);
        unset($_GET);
        header("refresh: $countdown; url=$page");
        exit(0);
    }

    public function isLoged(){
        if(!isset($_SESSION)) session_start ();
        if(!isset($_SESSION[SESSION_ID_FUNC])){
            return false;
        }
        return true;
    }

    public function logout(){
        if(!isset($_SESSION)) session_start ();
        if(isset($_SESSION)){
            session_destroy();
            $this->redirect("index.php");
        }
    }

    public function checkLogin(){
        $op = $this->filter("op");
        if( ! is_null($op) ) {
            switch ($op){
                case "login": $this->login(); break;
                case "logout": $this->logout(); break;
            }
        } 
    }

    private function login(){
        $usuario = $this->filter("login");
        $senha = $this->filter("senha");
        if(is_null($usuario) || is_null($senha)){
            $this->failInFunction("Todos os dados são necessários");
            $this->redirect("index.php");
        }
		
        $users_admins = array_keys($this->admins);
        if(in_array($usuario, $users_admins)){
            if(! strcmp($this->admins[$usuario], $senha) ){
                if(!isset($_SESSION)) session_start ();
                $_SESSION[SESSION_ID_FUNC] = 0;
                $_SESSION[SESSION_PERFIL_FUNC] = PERFIL_ADMINISTRADOR;
                $_SESSION[SESSION_LOJA_FUNC] = 0;
                $_SESSION[SESSION_LOJA_SIGLA_FUNC] = "";
                $_SESSION[SESSION_NOME_FUNC] = "Administrador ($usuario)";
            } else {
                $this->failInFunction("Dados Inválidos");
            }

        } else {

            include_once CONTROLLERS."funcionario.php";
            $controllerFuncionario = new FuncionarioController();
            $funcionario = $controllerFuncionario->getFuncionario($usuario, $senha);

            if(empty($funcionario->id)){
                    $this->failInFunction("Dados Inválidos");
            } else if (empty ($funcionario->perfil)){
                    $this->failInFunction("Você não pode entrar no sistema. Você não tem perfil de usuário");
            } else {
                if(!isset($_SESSION)) session_start ();
                $_SESSION[SESSION_ID_FUNC] = $funcionario->id;
                $_SESSION[SESSION_PERFIL_FUNC] = $funcionario->perfil;
                $_SESSION[SESSION_LOJA_FUNC] = $funcionario->loja;
                
                include_once CONTROLLERS."loja.php";
                $loja_controller = new LojaController();
                $loja = $loja_controller->getLoja($funcionario->loja);
                $_SESSION[SESSION_LOJA_SIGLA_FUNC] = $loja->sigla;
                
                $_SESSION[SESSION_NOME_FUNC] = $funcionario->nome;
            }
        }
        $this->redirect("index.php");

    }

}

?>
